package com.woniuxy.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

//全局异常处理器  用于捕获所有控制层的异常
@Component
public class GolbalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception ex) {
        ex.printStackTrace();
        FastJsonJsonView view = new FastJsonJsonView();
        response.setStatus(500);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("code", 500);
        // 判断异常类型
        if (ex instanceof UnknownAccountException) {
            map.put("message", "用户名不存在");
        } else if (ex instanceof IncorrectCredentialsException) {
            map.put("message", "密码错误");
        } else if (ex instanceof UnauthorizedException) {
            map.put("message", "非法访问");
        } else if (ex instanceof NotFullTimeException) {
            map.put("message", ex.getMessage());
        } else {
            map.put("message", "服务器内部异常");
        }
        view.setAttributesMap(map);
        return new ModelAndView(view);
    }

}
